package com.yvan.codeslave.action;

import com.google.common.base.Joiner;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.yvan.codeslave.PluginUtils;
import com.yvan.codeslave.batch.util;
import lombok.val;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.util.stream.Collectors;

public class CopySqlAction extends AnAction {
    public CopySqlAction() {
        super("copy insert sql");
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        val jwBuild = PluginUtils.getSelectStructs();

        //insert into t1 ()VALUES()
        val sb = new StringBuilder();
        for (val table : jwBuild.keys()) {
            sb.append("INSERT INTO ").append(table).append("(\n");
            val columns = jwBuild.keys(table);
            sb.append(Joiner.on(",\n").join(
                    columns.stream().map(k -> "  " + k).collect(Collectors.toList())
            ));
            sb.append("\n) VALUES (\n");
            sb.append(Joiner.on(",\n").join(
                    columns.stream().map(k -> "  #{" + util.hump(k) + "}").collect(Collectors.toList())
            ));
            sb.append("\n)\n\n");
        }
        setClipboardString(sb.toString());
    }

    /**
     * 把文本设置到剪贴板（复制）
     */
    public static void setClipboardString(String text) {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 封装文本内容
        Transferable trans = new StringSelection(text);
        // 把文本内容设置到系统剪贴板
        clipboard.setContents(trans, null);
    }
}
